<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="author" content="Cheresting" />
    <!-- 自动添加dayjs到全局 -->
    <script src="./publicJs/dayjs.min.js"></script>
    <!-- 自动添加vue到全局 -->
    <script src="./publicJs/vue.global.prod.js"></script>
    <!-- 自动添加axios到全局 -->
    <script src="./publicJs/axios.min.js"></script>
    <!-- 自动添加Cookies到全局 -->
    <script src="./publicJs/js.cookie.min.js"></script>
    <!-- 自动添加XLSX到全局 -->
    <script src="./publicJs/xlsx.core.min.js"></script>

    <link rel="stylesheet" href="./publicJs/element-plus.index.css" />
    <!-- 自动添加ElementPlus到全局 -->
    <script src="./publicJs/element-plus.index.full.js"></script>

    <title>智联项目号上传</title>
  </head>

  <body>
    <div id="app">
      <div v-loading="loading">
        <!-- 操作按钮 -->
        <el-row :gutter="10" class="marginTop10">
          <el-col :span="24" style="text-align: left">
            <el-upload
              ref="uploadRef"
              :auto-upload="false"
              :on-change="handleFileChange"
              :show-file-list="false"
              accept=".xlsx,.xls"
            >
              <template #trigger>
                <el-button type="primary">选择Excel文件</el-button>
              </template>
            </el-upload>
            <el-button type="success" @click="readExcel" :disabled="!selectedFile">读取Excel</el-button>
            <el-button type="warning" @click="uploadData" :disabled="tableData.length === 0">上传数据</el-button>
          </el-col>
        </el-row>

        <!-- 数据表格 -->
        <el-row :gutter="10" class="marginTop10">
          <el-col>
            <el-table :data="tableData" border stripe max-height="70vh" empty-text="请先读取Excel文件">
              <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
              <el-table-column prop="materialNo" label="物料号" width="200" align="center"></el-table-column>
              <el-table-column prop="materialName" label="物料描述" align="center"></el-table-column>
              <el-table-column prop="projectNo" label="项目号" width="200" align="center"></el-table-column>
              <el-table-column prop="result" label="上传结果" width="200" align="center"></el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </div>
    </div>
  </body>
  <script type="module">
    import myAxios from './myAxios/myAxios.js'
    const { createApp, ref, reactive } = Vue
    import { showSuccess, showWarning } from './hooks/useMyMessageBox.js'

    const app = createApp({
      name: 'ExcelUploader',
      setup() {
        const loading = ref(false)
        const selectedFile = ref(null)
        const tableData = reactive([])
        const uploadRef = ref(null)

        // 处理文件选择变化
        const handleFileChange = (file) => {
          selectedFile.value = file.raw
          tableData.length = 0 // 清空表格数据
        }

        // 读取Excel文件
        const readExcel = () => {
          if (!selectedFile.value) return

          loading.value = true
          const reader = new FileReader()

          reader.onload = (e) => {
            try {
              const data = new Uint8Array(e.target.result)
              const workbook = XLSX.read(data, { type: 'array' })
              const firstSheetName = workbook.SheetNames[0]
              const worksheet = workbook.Sheets[firstSheetName]

              // 将工作表转换为JSON
              const jsonData = XLSX.utils.sheet_to_json(worksheet)

              // 清空表格数据
              tableData.length = 0

              // 处理数据并填充表格
              jsonData.forEach((row) => {
                // 假设Excel中有"物料号"和"项目号"两列
                const materialNo = row['物料号'] || row['materialNo'] || ''
                const materialName = row['物料描述'] || row['materialName'] || ''
                const projectNo = row['项目号'] || row['projectNo'] || ''

                if (materialNo && projectNo) {
                  tableData.push({
                    materialNo: materialNo.toString(),
                    materialName: materialName.toString(),
                    projectNo: projectNo.toString(),
                    result: '待上传',
                  })
                }
              })

              if (tableData.length === 0) {
                showWarning('Excel中没有找到有效数据')
              } else {
                showSuccess(`成功读取 ${tableData.length} 条数据`)
              }
            } catch (error) {
              console.error('读取Excel出错:', error)
              showWarning('读取Excel文件失败')
            } finally {
              loading.value = false
            }
          }

          reader.onerror = () => {
            loading.value = false
            showWarning('读取文件出错')
          }

          reader.readAsArrayBuffer(selectedFile.value)
        }

        // 上传数据到服务器
        const uploadData = async () => {
          if (tableData.length === 0) return

          loading.value = true

          for (let i = 0; i < tableData.length; i++) {
            let materialNo = tableData[i]['materialNo']
            let materialName = tableData[i]['materialName']
            let projectNo = tableData[i]['projectNo']
            let processParam = `${materialNo}🈹${projectNo}`
            let result = await myAxios.post('陈帅廷更新智联项目号', processParam, '9911')

            tableData[i]['result'] = result
          }
          loading.value = false
          let failList = tableData.filter((item) => !item.result.includes('成功'))
          if (failList.length === 0) {
            showSuccess('上传成功')
          } else {
            let msg = failList.map((item) => item.materialNo).join('\n')
            showError('部分上传失败:', msg)
          }
          tableData.sort((a, b) => a.msg.localeCompare(b.msg))
        }

        return {
          loading,
          selectedFile,
          tableData,
          uploadRef,
          handleFileChange,
          readExcel,
          uploadData,
        }
      },
    })

    // 使用Element Plus
    app.use(ElementPlus)
    app.mount('#app')
  </script>
  <style>
    .marginTop10 {
      margin-top: 10px;
    }

    .el-button {
      margin-right: 10px;
    }

    .el-table {
      margin-top: 20px;
    }
  </style>
</html>
